<?php

namespace common\models\mongo;

use \yii\mongodb\ActiveRecord;

class BaseMongo extends ActiveRecord {

    /**
     * @var string $created_at , default 'created_at'
     */
    protected $t_created = 'created_at';
    /**
     * @var string $updated_at , default 'updated_at'
     */
    protected $t_updated = 'updated_at';
    /**
     * @var string $deleted_at , default 'deleted_at'
     */
    protected $t_deleted = 'deleted_at';

    /**
     * @var string $timeStamp ,'c' created_at,'u' updated_at,'d' deleted_at
     */
    protected $timeStamp = 'cu';

    /**
     * @var bool 软删除,默认关闭,软删除必须开启 timestamp='d'
     */
    private $softDel = false;


    protected function openTimeStamp() {
        $t = str_split($this->timeStamp, 1);

        if (count(array_diff($t, ['c', 'u', 'd'])) > 0) {
            return [];
        }

        $tArr = [];
        if (in_array('c', $t)) {
            $tArr[] = $this->t_created;
        }

        if (in_array('u', $t)) {
            $tArr[] = $this->t_updated;
        }

        if (in_array('d', $t)) {
            $tArr[] = $this->t_deleted;
            $this->softDel = true;
        }
        return $tArr;
    }

    public function attributes() {
        return array_merge([
            '_id',
        ], $this->openTimeStamp(), $this->attributesInit());
    }

    /**
     * @return array 初始化
     */
    public function attributesInit() {
        return [];
    }

    public function delete() {
        if ($this->softDel) {
            $attributeDel = $this->t_deleted;
            $this->$attributeDel = time();
            return $this->save();
        }
        return parent::delete();
    }

    public function softDeleteAll($condition = []) {
        if ($this->softDel) {
            $attributeDel = $this->t_deleted;
            return static::updateAll(array_merge([$this->$attributeDel => time(), $condition]));
        }
        return false;
    }

    public function beforeSave($insert) {

        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }
}